package com.yuyou.tas.lesson.controller;

import com.yuyou.tas.lesson.service.ILessonChapterService;
import com.yuyou.tas.lesson.service.ILessonService;
import com.yuyou.tas.lesson.service.comm.OrganLimitService;
import com.yuyou.tas.lesson.service.comm.Subj7SectLimitService;
import com.yuyou.tas.service.api.lesson.dto.LessonChapterDetDTO;
import com.yuyou.tas.service.api.lesson.dto.LessonChapterPageDTO;
import com.yuyou.tas.service.api.lesson.dto.LessonChapterPageDetDTO;
import com.yuyou.tas.service.api.lesson.entity.Lesson;
import com.yuyou.tas.util.bean.*;
import com.yuyou.tas.util.enums.OrganLimitEnums;
import com.yuyou.tas.util.enums.admin.AuthUserEnums;
import com.yuyou.tas.util.enums.lesson.LessonEnums;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(value = "LessonChapterController",description="课程讲次接口")
@Validated
@RestController
@RequestMapping(value = "/api/lessonChapter")
public class LessonChapterController extends BaseController {

	@Autowired
	private ILessonChapterService lessonChapterService;
	
	@Autowired
	private ILessonService lessonService;
	
	@Autowired
	private Subj7SectLimitService subj7SectLimitService;
	
	@Autowired
	private OrganLimitService organLimitService;
	
	
	@ApiOperation(value = "查询课程讲次")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "lessonId", value = "课程ID", paramType = "query", required = true),
			@ApiImplicitParam(name = "baseTrimesterId", value = "学期ID", paramType = "query", required = false),
			@ApiImplicitParam(name = "dataSubject", value = "科目ID", paramType = "query", required = false),
			@ApiImplicitParam(name = "baseSectionId", value = "年级ID", paramType = "query", required = false)})
	@RequestMapping(value = "/findLesChapterPage", method = {RequestMethod.GET, RequestMethod.POST })
	public ReturnResult<LessonChapterPageDetDTO> findLessonPage(
			HttpServletRequest request,
			@NotNull(message = "课程ID不能为空") Long lessonId,
			String baseTrimesterId, String dataSubject, String baseSectionId) throws Exception {
		PageParams pageParams=new PageParams(1,50);
		Map<String, Object> conditions = new HashMap<>();
		Pagination<LessonChapterPageDTO> queryPgn = new Pagination<>();
		LoginRedisObj user = this.getUserObj(request);
		conditions.put("lessonId", lessonId);
        conditions.put("baseTrimesterId", baseTrimesterId);
        conditions.put("dataSubject", dataSubject);
        conditions.put("baseSectionId", baseSectionId);

    	//权限校验
    	Lesson lesson=lessonService.selectByPrimaryKey(lessonId);
		subj7SectLimitService.checkByUserId(user.getUserId(), lesson.getDataSubject(), lesson.getBaseSectionId());
		
		if(!lesson.getIsStan().equals(1)){
			organLimitService.checkOrganByOrganId(user.getOrganizationId(), lesson.getId(), OrganLimitEnums.type.lesson);	
		}

		
    	conditions.put("organId", lesson.getAuthOrganizationId());
    	
        //科目年级数据权限
        //科目年级
        if(!user.getIsManager()){
			if(user.getUserType()==AuthUserEnums.type.teaching.getValue()){
	            /*conditions.put("subjectLimit", user.getDataSubjects());
	        	conditions.put("sectionLimit", user.getBaseSectionIds());*/
				conditions.put("subSecLimit" , user.getUserId());
			}		
        }
    	    	
		queryPgn.setConditions(conditions);
		queryPgn.setPageParams(pageParams);
		queryPgn.toBePage();
		List<LessonChapterPageDTO> list = lessonChapterService.findLessonChapterPageList(queryPgn);
		
		long initNum=list.stream().filter(item -> item.getStatus().equals(LessonEnums.status.init.getValue())).count();
		
		LessonChapterPageDetDTO res=new LessonChapterPageDetDTO();
		res.setList(list);
		res.setLessonId(lessonId);
		res.setChapterNum(lesson.getChapterNum());
		res.setName(lesson.getName());
		res.setStatus(lesson.getStatus());
		res.setDataSubject(lesson.getDataSubject());
		res.setAllPublic(initNum==0);
		res.setBaseLevelId(lesson.getBaseLevelId());
		res.setBaseSectionId(lesson.getBaseSectionId());	
		
		return ReturnResult.success(res);
	}
	
	@ApiOperation(value = "添加课程讲次")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "baseChapterIds", value = "讲次库ID,多个逗号分隔", paramType = "query", required = true),
			@ApiImplicitParam(name = "lessonId", value = "课程ID", paramType = "query", required = true),
			@ApiImplicitParam(name = "sortId", value = "课程讲次ID(如在添加的讲次在词讲次后)", paramType = "query", required = false)})
	@RequestMapping(value = "/addLesChapters", method = { RequestMethod.POST })
	public ReturnResult<String> addLessonChapter(
			HttpServletRequest request,
			@NotEmpty(message="讲次库ID不能为空") String[] baseChapterIds,
			@NotNull(message="课程ID不能为空") Long lessonId,
			Long sortId) throws Exception{	
		LoginRedisObj obj = this.getUserObj(request);
		ResBoolSimpleInfo<String> res=lessonChapterService.addLessonChapters(Arrays.asList(baseChapterIds).stream().map(item->Long.parseLong(item)).distinct().collect(Collectors.toList()),lessonId,obj.getIsSystem(),obj.getUserId(),sortId);
		return ReturnResult.returnRes(res.isSuccess(), res.getMessage(), null);
	}
		
	@ApiOperation(value = "删除课程讲次")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "lessonId", value = "课程ID", paramType = "query", required = true),
			@ApiImplicitParam(name = "id", value = "课程讲次ID", paramType = "query", required = true)})
	@RequestMapping(value = "/delLesChapters", method = { RequestMethod.POST })
	public ReturnResult<String> delLessonChapters(
			HttpServletRequest request,
			@NotNull(message="课程ID不能为空") Long lessonId,
			@NotNull(message="课程讲次ID不能为空") Long id) throws Exception{	
		LoginRedisObj obj = this.getUserObj(request);
		ResBoolSimpleInfo<String> res=lessonChapterService.delLessonChapters(lessonId,id,obj.getUserId());
		return ReturnResult.returnRes(res);
	}
	
	
	@ApiOperation(value = "课程讲次详情")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "lessonId", value = "课程ID", paramType = "query", required = true),
			@ApiImplicitParam(name = "id", value = "课程讲次ID", paramType = "query", required = true) })
	@RequestMapping(value = "/detailLesChapters", method = {RequestMethod.GET, RequestMethod.POST })
	public ReturnResult<LessonChapterDetDTO> detailLesChapters(
			HttpServletRequest request,
			@NotNull(message="课程ID不能为空") Long lessonId,
			@NotNull(message="课程讲次ID不能为空") Long id) throws Exception{	
		LoginRedisObj obj = this.getUserObj(request);
		ResBoolSimpleInfo<LessonChapterDetDTO> res=lessonChapterService.detailLesChapters(lessonId,id,obj.getUserId());		
		return ReturnResult.returnRes(res);
	}
	
	@ApiOperation(value = "更改课程讲次")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "lessonId", value = "课程ID", paramType = "query", required = true),
			@ApiImplicitParam(name = "id", value = "课程讲次ID", paramType = "query", required = true),
			@ApiImplicitParam(name = "baseChapterId", value = "讲次库ID", paramType = "query", required = true)})
	@RequestMapping(value = "/changeLesChapter", method = { RequestMethod.POST })
	public ReturnResult<String> changeLesChapter(
			HttpServletRequest request,
			@NotNull(message="课程ID不能为空") Long lessonId,
			@NotNull(message="课程讲次ID不能为空") Long id,
			@NotNull(message="讲次库ID不能为空") Long baseChapterId
			) throws Exception{	
		LoginRedisObj obj = this.getUserObj(request);
		ResBoolSimpleInfo<String> res=lessonChapterService.changeLessonChapters(lessonId,id,baseChapterId,obj.getUserId());
		return ReturnResult.returnRes(res);
	}
	
	@ApiOperation(value = "课程所有讲次排序")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "lessonId", value = "课程ID", paramType = "query", required = true),
		@ApiImplicitParam(name = "ids", value = "课程所有讲次ID,多个逗号分隔", paramType = "query", required = true)
		})
	@RequestMapping(value = "/sortLesChapters", method = { RequestMethod.POST })
	public ReturnResult<String> sortLessonChapters(
			HttpServletRequest request,
			@NotNull(message="课程ID不能为空") Long lessonId,
			@NotEmpty(message="课程讲次ID不能为空") String[] ids) throws Exception{	
		LoginRedisObj obj = this.getUserObj(request);
		ResBoolSimpleInfo<String> res=lessonChapterService.sortAllLesCha(lessonId,Arrays.asList(ids).stream().map(item->Long.parseLong(item)).collect(Collectors.toList()),obj.getUserId());
		return ReturnResult.returnRes(res);
	}
	
    @ApiOperation(value = "发布课程讲次")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "lessonId", value = "课程ID", paramType = "query", required = true),
		@ApiImplicitParam(name = "ids", value = "课程讲次ID,多个逗号分隔", paramType = "query", required = true) })
    @RequestMapping(value = "/publishLesChapter" ,method = RequestMethod.POST)
    public ReturnResult<String> publishLesson(HttpServletRequest request,
    		@NotNull(message="课程ID不能为空") Long lessonId,
    		@NotEmpty(message="课程讲次ID不能为空") String[] ids) throws Exception{ 
    	LoginRedisObj obj = this.getUserObj(request);
    	ResBoolSimpleInfo<String> res=lessonChapterService.publishLesChapters(lessonId,Arrays.asList(ids).stream().map(item->Long.parseLong(item)).distinct().collect(Collectors.toList()),obj.getUserId());   	
    	return ReturnResult.returnRes(res);
    	
    	
    }
	
	
//	@ApiOperation(value = "隐藏课程讲次")
//	@ApiImplicitParams({
//			@ApiImplicitParam(name = "lessonId", value = "课程ID", paramType = "query", required = true),
//			@ApiImplicitParam(name = "id", value = "课程讲次ID不能为空", paramType = "query", required = true),
//			@ApiImplicitParam(name = "isHide", value = "是否隐藏：0:否,1:是", paramType = "query", required = true)})
//	@RequestMapping(value = "/hideLesChapters", method = {RequestMethod.GET, RequestMethod.POST })
//	public ReturnResult<LessonChapterDetDTO> hideLesChapters(
//			HttpServletRequest request,
//			@NotNull(message="课程ID不能为空") Long lessonId,
//			@NotNull(message="课程讲次ID不能为空") Long id,
//			@NotNull(message="是否隐藏不能为空") Integer isHide) throws Exception{	
//		ResBoolSimpleInfo<String> res=new ResBoolSimpleInfo<String>();
//		LoginRedisObj obj = this.getUserObj(request);
//		res=lessonChapterService.hideLesChapters(lessonId,id,isHide,obj.getUserId());		
//		return ReturnResult.returnRes(res);
//	}


}
